package com.wanli.agent.homepage.adapter;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.wanli.agent.R;
import com.wanli.agent.base.DataCallBack;
import com.wanli.agent.bean.BaseResponseBean;
import com.wanli.agent.bean.GetWxMercIdBean;
import com.wanli.agent.bean.MerchantDetailsBean;
import com.wanli.agent.bean.StoreDeatilsBean;
import com.wanli.agent.bean.UserInfoBean;
import com.wanli.agent.event.StoreDataEvent;
import com.wanli.agent.homepage.EBankStoreDataActivity;
import com.wanli.agent.homepage.StoreDataActivity;
import com.wanli.agent.homepage.StoreSpeedRateActivity;
import com.wanli.agent.homepage.model.HomePageModelImpl;
import com.wanli.agent.utils.DateTimeUtil;
import com.wanli.agent.utils.FastClickUtils;
import com.wanli.agent.utils.SPManager;
import com.wanli.agent.utils.StringUtils;
import com.wanli.agent.utils.ToastUtil;
import com.wanli.agent.widget.CommonNoTitleDialog;

import org.greenrobot.eventbus.EventBus;
import org.jsoup.helper.StringUtil;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import ch.ielse.view.SwitchView;

/**
 * Author: HWC
 * Description: 服务商列表
 */
public class MerchantDetailsListAdapter extends RecyclerView.Adapter<MerchantDetailsListAdapter.ViewHolder> {

    private List<MerchantDetailsBean.DataBean.StoreListBean> listsBeans;
    private int id;
    private Context context;
    private CommonNoTitleDialog.Builder dialogBuild;
    private UserInfoBean userInfoBean;

    private onClickMyTextView onClickMyTextView;

    //接口回调
    public interface onClickMyTextView {
        public void myTextViewClick(String name);
    }

    public void setOnClickMyTextView(onClickMyTextView onClickMyTextView) {
        this.onClickMyTextView = onClickMyTextView;
    }


    public MerchantDetailsListAdapter(List<MerchantDetailsBean.DataBean.StoreListBean> listsBeans,int id) {
        this.listsBeans = listsBeans;
        this.id = id;
        userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        context = viewGroup.getContext();
        View inflate = LayoutInflater.from(context).inflate(R.layout.item_merchant_details_list, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(inflate);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        MerchantDetailsBean.DataBean.StoreListBean dataBean = listsBeans.get(position);
        holder.tvName.setText(dataBean.getName());
        holder.tvReason.setVisibility(View.GONE);
        holder.tvStoreNo.setText("编号：" + dataBean.getStore_no());
        String ys_merc_id = StringUtils.nullString(dataBean.getYs_merc_id());
        String yinsheng_sys_flowId = StringUtils.nullString(dataBean.getYinsheng_sys_flowId());
        String thirdMercId = StringUtils.nullString(dataBean.getThirdMercId());
        holder.tv_ys_merc_id.setText("商户编号：" + ys_merc_id);
        holder.tv_yinsheng_sys_flowId.setText("入网流水号：" +yinsheng_sys_flowId);
        holder.tv_wechat_merchant_number.setText("微信商户号：" + thirdMercId);
        if ("".equals(ys_merc_id)){
            holder.tv_ys_merc_id.setVisibility(View.GONE);
        }else {
            holder.tv_ys_merc_id.setVisibility(View.VISIBLE);
        }


        if ("".equals(yinsheng_sys_flowId)){
            holder.tv_yinsheng_sys_flowId.setVisibility(View.GONE);
        }else {
            holder.tv_yinsheng_sys_flowId.setVisibility(View.VISIBLE);
        }

        int channel_type = dataBean.getChannel_type();
        if (channel_type==2){
            holder.tv_channel_type.setText("智能版");
        }else {
            holder.tv_channel_type.setText("标准版");
        }
        holder.tvReason.setVisibility(View.GONE);
        holder.tvFeedback.setVisibility(View.GONE);
        int sign_status = dataBean.getSign_status();

        //签约状态 0-申请中 1-待签署 2-已创建（成功最终状态） 3-已作废 4-已过期 7-创建失败 8-合同已生成
        if (sign_status == 0) {
            holder.tv_sign_status.setText("签约状态：申请中");
        } else if (sign_status == 1) {
            holder.tv_sign_status.setText("签约状态：待签署");
        } else if (sign_status == 2) {
            holder.tv_sign_status.setText("签约状态：已创建");
        } else if (sign_status == 3) {
            holder.tv_sign_status.setText("签约状态：已作废");
        } else if (sign_status == 4) {
            holder.tv_sign_status.setText("签约状态：已过期");
        } else if (sign_status == 7) {
            holder.tv_sign_status.setText("签约状态：创建失败");
        } else if (sign_status == 8) {
            holder.tv_sign_status.setText("签约状态：合同已生成");
        } else {
            holder.tv_sign_status.setText("签约状态：未知");
        }

        int pay_channel_status = dataBean.getPay_channel_status();


        Log.e("pay_channel_status==",pay_channel_status+"");

        if (pay_channel_status == 0) {
            holder.tvInformation.setText("查看资料");
            holder.tvStatus.setText("待提交资料");
        } else if (dataBean.getPay_channel_status() == 1) {
            holder.tvInformation.setText("查看资料");
            holder.tvStatus.setText("等待审核");

            if (!TextUtils.isEmpty(dataBean.getReject_msg())) {
                holder.tvFeedback.setVisibility(View.VISIBLE);
                holder.tvFeedback.setText("审核反馈：" + dataBean.getReject_msg());
            }
        } else if (dataBean.getPay_channel_status() == 2) {
            holder.tvInformation.setText("查看资料");

            holder.tvStatus.setText("正在审核");
            if (!TextUtils.isEmpty(dataBean.getReject_msg())) {
                holder.tvFeedback.setVisibility(View.VISIBLE);
                holder.tvFeedback.setText("审核反馈：" + dataBean.getReject_msg());
            }
        } else if (dataBean.getPay_channel_status() == 3) {
            holder.tvInformation.setText("查看资料");

            holder.tvStatus.setText("已通过");
        } else if (dataBean.getPay_channel_status() == 4) {
            holder.tvInformation.setText("修改资料");
            holder.tvStatus.setText("已驳回");
            holder.tvReason.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(dataBean.getReject_msg())) {
                holder.tvFeedback.setVisibility(View.VISIBLE);
                holder.tvFeedback.setText("审核反馈：" + dataBean.getReject_msg());
            }
        } else if (dataBean.getPay_channel_status() == 5) {
            holder.tvInformation.setText("查看资料");

            holder.tvStatus.setText("正在审核");
            if (!TextUtils.isEmpty(dataBean.getReject_msg())) {
                holder.tvFeedback.setVisibility(View.VISIBLE);
                holder.tvFeedback.setText("审核反馈：" + dataBean.getReject_msg());
            }
        } else {
            holder.tvInformation.setText("查看资料");
        }

        if (dataBean.getPay_channel_status() == 3&&id==1){
            holder.tvSetHuabei.setVisibility(View.VISIBLE);
        }else {
            holder.tvSetHuabei.setVisibility(View.GONE);
        }



        String reject_msg = dataBean.getReject_msg();

        if ((pay_channel_status == 1 || pay_channel_status == 2 || pay_channel_status == 5) && (sign_status == 0 || sign_status == 1 || sign_status == 4 || sign_status == 3 || sign_status == 7 || sign_status == 8) && StringUtils.nullStringZrg(reject_msg).contains("转人工")) {
            holder.tv_re_sign.setVisibility(View.VISIBLE);
        } else {
            holder.tv_re_sign.setVisibility(View.GONE);
        }

        holder.tvTime.setText("创建时间：" + DateTimeUtil.format7(new Date(Long.parseLong(dataBean.getCreate_time()) * 1000)));

        holder.tv_rate.setText("费率：" + dataBean.getRate());

        if (TextUtils.isEmpty(thirdMercId)) {
            holder.tv_wechat_merchant_number.setVisibility(View.GONE);
            holder.tv_wechat_official_account.setVisibility(View.VISIBLE);
        } else {
            holder.tv_wechat_merchant_number.setVisibility(View.VISIBLE);
            holder.tv_wechat_official_account.setVisibility(View.GONE);
        }


        holder.tvReason.setOnClickListener(view -> {
            dialogBuild = new CommonNoTitleDialog.Builder((Activity) context);
            dialogBuild.setMessage(dataBean.getReject_msg());
            dialogBuild.setPositiveButton("确定", v -> {
                dialogBuild.dismiss();
            });
            dialogBuild.setNegativeButton("取消", v -> dialogBuild.dismiss());
            dialogBuild.setCancelable(false);
            dialogBuild.show();
        });


        holder.tvInformation.setOnClickListener(v -> {
            if (FastClickUtils.isFastClick()) {
                return;
            }
            new HomePageModelImpl().requestStoreProfile(dataBean.getStore_no(), new DataCallBack<StoreDeatilsBean>() {
                @Override
                public void onSuccessful(StoreDeatilsBean bean) {
                    if (bean.getData() != null) {
                        EventBus.getDefault().postSticky(new StoreDataEvent(bean.getData()));
                        if (bean.getData().getQuick_income() == 2) {
                            Intent intent = new Intent(context, EBankStoreDataActivity.class);
                            context.startActivity(intent);
                        } else {
                            if (dataBean.getPay_channel_status() == 4) {
                                Intent intent = new Intent(context, StoreDataActivity.class);
                                intent.putExtra("isShow", "1");
                                context.startActivity(intent);
                            } else {
                                Intent intent = new Intent(context, StoreDataActivity.class);
                                intent.putExtra("isShow", "0");
                                context.startActivity(intent);
                            }
                        }
                    }
                }

                @Override
                public void onFailed(String msg, String code) {

                }
            });
        });

        holder.tvSetHuabei.setOnClickListener(v -> {
            Intent intent = new Intent(context, StoreSpeedRateActivity.class);
            intent.putExtra("store_no", dataBean.getStore_no());
            intent.putExtra("rate", dataBean.getRate());
            context.startActivity(intent);
        });
        holder.tv_ys_merc_id.setOnClickListener(v -> {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", dataBean.getYs_merc_id());
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            ToastUtil.showShort("复制成功");
        });
        holder.tv_yinsheng_sys_flowId.setOnClickListener(v -> {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", dataBean.getYinsheng_sys_flowId());
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            ToastUtil.showShort("复制成功");
        });
        holder.tv_wechat_merchant_number.setOnClickListener(v -> {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", dataBean.getThirdMercId());
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            ToastUtil.showShort("复制成功");
        });
        holder.tvStoreNo.setOnClickListener(v -> {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", dataBean.getStore_no());
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            ToastUtil.showShort("复制成功");
        });

        holder.tv_wechat_official_account.setOnClickListener(v -> {
            if (FastClickUtils.isFastClick()) {
                return;
            }
            new HomePageModelImpl().requestGetWxMercId(dataBean.getStore_no(), dataBean.getYs_merc_id(), new DataCallBack<GetWxMercIdBean>() {
                @Override
                public void onSuccessful(GetWxMercIdBean bean) {
                    if (bean.getData() != null) {
                        String thirdMercId = bean.getData().getThirdMercId();
                        dataBean.setThirdMercId(thirdMercId);
                        notifyDataSetChanged();
                    }
                }

                @Override
                public void onFailed(String msg, String code) {

                }
            });
        });

        if (userInfoBean != null) {
            if (userInfoBean.getData().getId() == 1) {
                holder.llStoreStatus.setVisibility(View.VISIBLE);
            } else {
                holder.llStoreStatus.setVisibility(View.GONE);
            }
        } else {
            holder.llStoreStatus.setVisibility(View.GONE);
        }
        if (dataBean.getIs_close() == 1) {
            holder.switchview.setOpened(true);
            holder.tvStoreStatus.setText("限制交易：已限制");
            holder.tvStoreStatus.setTextColor(context.getResources().getColor(R.color.theme_color));
        } else {
            holder.switchview.setOpened(false);
            holder.tvStoreStatus.setText("限制交易：未限制");
            holder.tvStoreStatus.setTextColor(context.getResources().getColor(R.color.text_color_5));
        }

        if (onClickMyTextView != null) {
            holder.tv_re_sign.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    onClickMyTextView.myTextViewClick(dataBean.getStore_no());
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return listsBeans.size() == 0 ? 0 : listsBeans.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_time)
        TextView tvTime;
        @BindView(R.id.tv_status)
        TextView tvStatus;
        @BindView(R.id.tv_sign_status)
        TextView tv_sign_status;
        @BindView(R.id.tv_re_sign)
        TextView tv_re_sign;
        @BindView(R.id.tv_yinsheng_sys_flowId)
        TextView tv_yinsheng_sys_flowId;
        @BindView(R.id.tv_name)
        TextView tvName;
        @BindView(R.id.tv_store_no)
        TextView tvStoreNo;
        @BindView(R.id.tv_ys_merc_id)
        TextView tv_ys_merc_id;
        @BindView(R.id.tv_feedback)
        TextView tvFeedback;
        @BindView(R.id.tv_reason)
        TextView tvReason;
        @BindView(R.id.tv_set_huabei)
        TextView tvSetHuabei;
        @BindView(R.id.tv_information)
        TextView tvInformation;
        @BindView(R.id.tv_store_status)
        TextView tvStoreStatus;
        @BindView(R.id.switchview)
        SwitchView switchview;
        @BindView(R.id.ll_store_status)
        LinearLayout llStoreStatus;
        @BindView(R.id.tv_wechat_official_account)
        TextView tv_wechat_official_account;
        @BindView(R.id.tv_wechat_merchant_number)
        TextView tv_wechat_merchant_number;
        @BindView(R.id.tv_rate)
        TextView tv_rate;
        @BindView(R.id.tv_channel_type)
        TextView tv_channel_type;


        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

            switchview.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
                @Override
                public void toggleToOn(SwitchView view) {
                    MerchantDetailsBean.DataBean.StoreListBean bean = listsBeans.get(getAdapterPosition());
                    requestChangeStoreCloseStatus(bean, bean.getStore_no(), "1");
                }

                @Override
                public void toggleToOff(SwitchView view) {
                    MerchantDetailsBean.DataBean.StoreListBean bean = listsBeans.get(getAdapterPosition());
                    requestChangeStoreCloseStatus(bean, bean.getStore_no(), "0");
                }
            });
        }
    }

    public void requestChangeStoreCloseStatus(MerchantDetailsBean.DataBean.StoreListBean storeListBean, String store_no, String is_close) {
        new HomePageModelImpl().requestChangeStoreCloseStatus(store_no, is_close, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort("设置成功");
                storeListBean.setIs_close(Integer.parseInt(is_close));
                notifyDataSetChanged();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }
}
